<template>
    <div class="upload-image">
      <a-upload
        v-model:file-list="fileList"
        :action="action"
        list-type="picture-card"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div v-if="fileList.length < limit">
          <a-icon type="plus" />
          <div class="upload-text">上传</div>
        </div>
      </a-upload>
      <a-modal
        v-model:open="previewVisible"
        :title="previewTitle"
        :footer="null"
        @cancel="handleCancel"
      >
        <img :src="previewImage" alt="preview" style="width: 100%" />
      </a-modal>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { ref } from 'vue';
  import { UploadChangeParam } from 'ant-design-vue';
  
  interface Props {
    action:'',//上传服务接口
    limit: number; // 上传图片数量限制
    fileListJson?: any[]; // 初始文件列表（回显数据）
  }
  
  const props = defineProps<Props>();
  const fileList = ref<any[]>([]);
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');
  
  // 处理预览图片
  const handlePreview = (file) => {
    if (!file.url && file.originFileObj) {
      const reader = new FileReader();
      reader.onload = (e) => {
        file.preview = e.target.result;
        previewImage.value = file.preview;
      };
      reader.readAsDataURL(file.originFileObj);
    } else {
      previewImage.value = file.url || file.preview;
    }
    previewVisible.value = true;
    previewTitle.value = file.name || '';
  };
  
  // 处理上传变化
  const handleChange = (info: UploadChangeParam) => {
    const fileListCopy = [...info.fileList];
    fileListCopy.forEach(file => {
      if (file.response) {
        // 假设后端返回的数据中包含url字段作为文件的访问地址
        file.url = file.response.url;
      }
    });
    fileList.value = fileListCopy;
    // 如果需要，可以在这里处理上传完成后的逻辑，例如关闭模态框等
  };
  
  // 处理取消预览
  const handleCancel = () => {
    previewVisible.value = false;
  };
  
  // 初始化文件列表（回显数据）
  if (props.fileListJson) {
    fileList.value = props.fileListJson.map(item => ({
      uid: item.uid || Date.now() + Math.random(), // 确保每个文件都有一个唯一的uid
      name: item.name,
      url: item.url,
      status: 'done', // 标记文件已经上传完成
    }));
  }
  </script>
  
  <style scoped>
  .upload-image .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  
  .upload-image .ant-upload-select-picture-card .upload-text {
    margin-top: 8px;
    color: #666;
  }
  </style>